package com.campus.customer.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.common.bean.common.PageQueryParam;
import com.campus.customer.entity.Canteen;
import com.campus.customer.entity.Merchant;
import com.campus.customer.mapper.CanteenMapper;
import com.campus.customer.mapper.MerchantMapper;
import com.campus.customer.vo.CanteenVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 食堂表 服务实现类
 * </p>
 *
 * @author ZhaoYuJie
 * @since 2025-04-02
 */
@Service
public class CanteenService extends ServiceImpl<CanteenMapper, Canteen> {
    @Autowired
    private MerchantMapper merchantMapper;
    public PageInfo<CanteenVo> pageList(PageQueryParam param) {
        PageInfo<Canteen> pageInfo = PageHelper.startPage(param.getPageNo(), param.getPageSize())
                .doSelectPageInfo(() -> baseMapper.selectList(Wrappers.lambdaQuery(Canteen.class).eq(Canteen::getStatus, true)));

        // 将 Canteen 对象转换为 CanteenVo 对象
        List<CanteenVo> canteenVoList = pageInfo.getList().stream()
                .map(canteen -> {
                    CanteenVo canteenVo = new CanteenVo();
                    BeanUtil.copyProperties(canteen, canteenVo);
                    canteenVo.setMerchantCount(merchantMapper.selectCount(Wrappers.lambdaQuery(Merchant.class).eq(Merchant::getCanteenId, canteen.getId())));
                    return canteenVo;
                })
                .collect(Collectors.toList());

        PageInfo<CanteenVo> canteenVoPageInfo = new PageInfo<>(canteenVoList);
        canteenVoPageInfo.setTotal(pageInfo.getTotal());
        canteenVoPageInfo.setPages(pageInfo.getPages());
        canteenVoPageInfo.setPageNum(pageInfo.getPageNum());
        canteenVoPageInfo.setPageSize(pageInfo.getPageSize());

        return canteenVoPageInfo;
    }

    public CanteenVo getCanteenById(Integer id) {
        Canteen canteen = getById(id);
        if (canteen != null) {
            CanteenVo canteenVo = new CanteenVo();
            BeanUtil.copyProperties(canteen, canteenVo);
            canteenVo.setMerchantCount(merchantMapper.selectCount(Wrappers.lambdaQuery(Merchant.class).eq(Merchant::getCanteenId, id)));
            return canteenVo;
        }
        return null;
    }
}
